﻿using System;
using System.Collections.Generic;
using System.Text;
using Yawf.Core.Utils;
using System.IO;
using Yawf.Web.Managers.Entities;

namespace Yawf.Web.Managers
{
    class FreemarkerViewLoader : freemarker.cache.TemplateLoader
    {
        #region TemplateLoader Members

        void freemarker.cache.TemplateLoader.closeTemplateSource(object obj)
        {
            /*do nothing*/
        }

        object freemarker.cache.TemplateLoader.findTemplateSource(string resource)
        {
            FileInfo fileInfo = findResource(resource);
			if (fileInfo.Exists) {
                return fileInfo;
            }
            return null;
        }

        private FileInfo findResource(string resource)
        {
            return new FileInfo(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/" + resource);
        }

        long freemarker.cache.TemplateLoader.getLastModified(object resource)
        {
            return ((FileInfo)resource).LastWriteTimeUtc.ToFileTimeUtc();
        }

        java.io.Reader freemarker.cache.TemplateLoader.getReader(object resource, string encoding)
        {
            FileInfo fileInfo = (FileInfo)resource;
			if (fileInfo.Extension != null && fileInfo.Extension.ToUpper() == ".XML") {
                View view = new View(fileInfo.FullName);
				return new java.io.StringReader(view.Content);
			}
            return new java.io.InputStreamReader(new java.io.FileInputStream(fileInfo.FullName), java.nio.charset.Charset.forName("utf-8"));
        }

        #endregion
    }
}
